package com.ydl.iec.thrid;
import org.openmuc.j60870.*;

import java.net.*;
import java.io.*;

/**
 * @Author : 汪洋
 * @CreateTime : 2023/11/29
 * @Description :
 * @Version : v1.0
 */
//由于可能要监听多个从站，这里使用多线程处理
public class J60870Client implements Runnable {

    private J60870ClientListener listener;
    //连接类
    private Connection connection;
    //连接参数，可以配置的参数有好多，比如t0,t1,t2等等
    private ClientConnectionBuilder clientConnectionBuilder;

    public J60870Client(){
        try {
            //获取server端、从站的ip地址对象，这里使用本地ip
            InetAddress address = InetAddress.getByName("127.0.0.1");
            //创建连接参数对象
            clientConnectionBuilder = new ClientConnectionBuilder(address);
            //设置socket的连接超时时间
            clientConnectionBuilder.setConnectionTimeout(60000);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            //主站与从站连接
            connection = clientConnectionBuilder.build();
            //配置数据回调类
            listener = new J60870ClientListener();
            connection.startDataTransfer(listener);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    //关闭连接
    public void disconnect() {
        try {
            this.connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void createHaoLing() {
        // 创建总召唤命令的ASDU
        ASdu asdu = new ASdu(ASduType.C_IC_NA_1, false,
                CauseOfTransmission.ACTIVATION,
                false, false, 0, 0);

        // 设置ASDU的传输原因

        // 添加总召唤命令

    }
}
